<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import axios from 'axios'

const props = defineProps<{
  eventId?: number
}>()

interface Registration {
  regID: number
  gameID: number
  eventID: number
  userID: number
  regTime: string
  isUsing: number
}

interface User {
  userID: number
  numID: string
  username: string
  password: string
  email: string
  phone: string
  department: string
  grade: string
  major: string
  createTime: string
}

interface RegistrationInfo {
  registration: Registration
  user: User
}

const currentEventId = ref(props.eventId || null)
const registrations = ref<RegistrationInfo[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(8) // 每页显示10条数据
const showRejectModal = ref(false)
const selectedRegistration = ref<RegistrationInfo | null>(null)
const rejectReason = ref('')
const filterStatus = ref('all') // 添加筛选状态
const currentGameId = ref<number|null>(null) // 添加gameId的存储
const showSuccessModal = ref(false) // 添加成功弹窗控制

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(filteredRegistrations.value.length / pageSize.value)
})

// 计算当前页的数据
const paginatedRegistrations = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return filteredRegistrations.value.slice(startIndex, endIndex)
})

// 根据筛选状态过滤数据
const filteredRegistrations = computed(() => {
  if (filterStatus.value === 'all') {
    return registrations.value
  } else if (filterStatus.value === 'approved') {
    return registrations.value.filter(item => item.registration.isUsing === 1)
  } else if (filterStatus.value === 'pending') {
    return registrations.value.filter(item => item.registration.isUsing === 0)
  }
  return registrations.value
})

const goBack = () => {
  // 传递正确的gameId值，确保返回到正确的比赛项目列表
  window.dispatchEvent(new CustomEvent('showGameEvent', {
    detail: { type: 'backToEventsList', gameId: currentGameId.value }
  }))
}

// 页面切换函数
const changePage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 获取报名信息
const fetchRegistrations = async () => {
  if (!currentEventId.value) return
  
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get(`http://localhost:8080/event/registrations?eventId=${currentEventId.value}`, {
      headers: {
        'token': token
      }
    })
    
    registrations.value = response.data.registrations.sort((a: RegistrationInfo, b: RegistrationInfo) => {
      // 未审批的信息排在前面，已通过的信息次之，未通过的信息排在最后
      if (a.registration.isUsing !== b.registration.isUsing) {
        // 未审批 (0) 应该排在最前面
        if (a.registration.isUsing === 0) return -1
        if (b.registration.isUsing === 0) return 1
        
        // 已通过 (1) 应该排在中间
        if (a.registration.isUsing === 1) return -1
        if (b.registration.isUsing === 1) return 1
        
        // 未通过 (2) 应该排在最后
      }
      
      // 相同状态内按申请时间排序
      return new Date(a.registration.regTime).getTime() - new Date(b.registration.regTime).getTime()
    })
    
    // 重置到第一页
    currentPage.value = 1
  } catch (error) {
    console.error('获取报名信息失败:', error)
  } finally {
    loading.value = false
  }
}

// 提交报名名单
const submitRegistrationList = async () => {
  if (!currentGameId.value || !currentEventId.value) {
    console.error('缺少必要的参数：gameId 或 eventId')
    return
  }

  // 确保参数是整数类型
  const gameId = parseInt(currentGameId.value.toString(), 10)
  const eventId = parseInt(currentEventId.value.toString(), 10)
  
  // 检查参数是否为有效数字
  if (isNaN(gameId) || isNaN(eventId)) {
    console.error('参数类型错误：gameId 和 eventId 必须是有效的整数')
    return
  }

  console.log('提交报名名单参数:', {
    gameId: gameId,
    eventId: eventId
  })

  try {
    const token = localStorage.getItem('token')
    console.log('使用的token:', token)
    
    const response = await axios.post(
      `http://localhost:8080/score/batchAdd?gameId=${gameId}&eventId=${eventId}`,
      null, // 不需要请求体
      {
        headers: {
          'token': token
        }
      }
    )
    console.log('提交报名名单成功', response.data)
    // 显示成功弹窗
    showSuccessModal.value = true
    // 可以在这里添加成功提示
  } catch (error: any) {
    console.error('提交报名名单失败:', error)
    // 可以在这里添加失败提示
    if (error.response) {
      console.error('错误响应数据:', error.response.data)
      console.error('错误状态码:', error.response.status)
      console.error('错误响应头:', error.response.headers)
    }
  }
}

// 暴露初始化方法供父组件调用
const init = (eventId: number, gameId?: number) => {
  currentEventId.value = eventId
  if (gameId) {
    currentGameId.value = gameId
  }
  fetchRegistrations()
}

// 监听事件ID变化
watch(currentEventId, (newVal) => {
  if (newVal) {
    fetchRegistrations()
  }
})

// 处理通过审核
const handleApprove = async (registration: RegistrationInfo) => {
  try {
    const token = localStorage.getItem('token')
    await axios.post(`http://localhost:8080/organizer/approveReg?regId=${registration.registration.regID}`, {}, {
      headers: {
        'token': token
      }
    })
    
    // 更新本地状态
    registration.registration.isUsing = 1 // 1表示已通过
    
    // 重新排序列表以反映状态变更
    registrations.value = [...registrations.value].sort((a: RegistrationInfo, b: RegistrationInfo) => {
      // 未审批的信息排在前面，已通过的信息次之，未通过的信息排在最后
      if (a.registration.isUsing !== b.registration.isUsing) {
        // 未审批 (0) 应该排在最前面
        if (a.registration.isUsing === 0) return -1
        if (b.registration.isUsing === 0) return 1
        
        // 已通过 (1) 应该排在中间
        if (a.registration.isUsing === 1) return -1
        if (b.registration.isUsing === 1) return 1
        
        // 未通过 (2) 应该排在最后
      }
      
      // 相同状态内按申请时间排序
      return new Date(a.registration.regTime).getTime() - new Date(b.registration.regTime).getTime()
    })
    
    // 显示成功消息（这里可以根据需要添加）
    console.log('审核通过成功')
  } catch (error) {
    console.error('审核通过失败:', error)
    // 显示错误消息（这里可以根据需要添加）
  }
}

// 打开拒绝弹窗
const openRejectModal = (registration: RegistrationInfo) => {
  selectedRegistration.value = registration
  showRejectModal.value = true
  rejectReason.value = ''
}

// 处理拒绝审核
const handleReject = async () => {
  if (!selectedRegistration.value || !rejectReason.value.trim()) {
    return
  }
  
  try {
    const token = localStorage.getItem('token')
    await axios.delete(`http://localhost:8080/organizer/deleteReg?regId=${selectedRegistration.value.registration.regID}`, {
      headers: {
        'token': token
      }
    })
    
    // 更新本地状态
    selectedRegistration.value.registration.isUsing = 2 // 2表示未通过
    
    // 重新排序列表以反映状态变更
    registrations.value = [...registrations.value].sort((a: RegistrationInfo, b: RegistrationInfo) => {
      // 未审批的信息排在前面，已通过的信息次之，未通过的信息排在最后
      if (a.registration.isUsing !== b.registration.isUsing) {
        // 未审批 (0) 应该排在最前面
        if (a.registration.isUsing === 0) return -1
        if (b.registration.isUsing === 0) return 1
        
        // 已通过 (1) 应该排在中间
        if (a.registration.isUsing === 1) return -1
        if (b.registration.isUsing === 1) return 1
        
        // 未通过 (2) 应该排在最后
      }
      
      // 相同状态内按申请时间排序
      return new Date(a.registration.regTime).getTime() - new Date(b.registration.regTime).getTime()
    })
    
    // 关闭弹窗
    showRejectModal.value = false
    
    // 显示成功消息（这里可以根据需要添加）
    console.log('审核拒绝成功')
  } catch (error) {
    console.error('审核拒绝失败:', error)
    // 显示错误消息（这里可以根据需要添加）
  }
}

// 处理取消报名
const handleCancelRegistration = async (registration: RegistrationInfo) => {
  try {
    const token = localStorage.getItem('token')
    // 使用DELETE方法请求 organizer/deleteReg 接口
    await axios.delete(`http://localhost:8080/organizer/deleteReg?regId=${registration.registration.regID}`, {
      headers: {
        'token': token
      }
    })
    
    // 从列表中移除该报名信息
    registrations.value = registrations.value.filter(item => item.registration.regID !== registration.registration.regID)
    
    // 显示成功消息
    console.log('取消报名成功')
  } catch (error) {
    console.error('取消报名失败:', error)
    // 显示错误消息
  }
}

// 设置筛选状态
const setFilterStatus = (status: string) => {
  filterStatus.value = status
  currentPage.value = 1 // 切换筛选时回到第一页
}

defineExpose({ init })
</script>

<template>
  <div class="event-register-management">
    <div class="header">
      <div class="header-actions">
        <div class="filter-buttons">
          <button 
            :class="{ active: filterStatus === 'all' }" 
            @click="setFilterStatus('all')"
          >
            全部
          </button>
          <button 
            :class="{ active: filterStatus === 'approved' }" 
            @click="setFilterStatus('approved')"
          >
            已通过
          </button>
          <button 
            :class="{ active: filterStatus === 'pending' }" 
            @click="setFilterStatus('pending')"
          >
            未审批
          </button>
        </div>
        <button class="submit-button" @click="submitRegistrationList" :disabled="!currentEventId">提交报名名单</button>
        <button class="back-button" @click="goBack">返回项目列表</button>
      </div>
    </div>
    
    <div class="content">
      <div v-if="loading" class="loading">
        加载中...
      </div>
      
      <div v-else-if="!currentEventId" class="empty-state">
        请从比赛项目列表选择一个项目进行管理
      </div>
      
      <div v-else-if="filteredRegistrations.length === 0" class="empty-state">
        暂无报名信息
      </div>
      
      <div v-else class="registrations-list">
        <table class="registrations-table">
          <thead>
            <tr>
              <th>申请时间</th>
              <th>学号</th>
              <th>姓名</th>
              <th>学院</th>
              <th>报名状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in paginatedRegistrations" :key="item.registration.regID">
              <td>{{ new Date(item.registration.regTime).toLocaleString() }}</td>
              <td>{{ item.user.numID }}</td>
              <td>{{ item.user.username }}</td>
              <td>{{ item.user.department }}</td>
              <td>
                <div class="status" v-if="item.registration.isUsing === 0">未审批</div>
                <div class="status approved" v-else-if="item.registration.isUsing === 1">已通过</div>
                <div class="status rejected" v-else-if="item.registration.isUsing === 2">未通过</div>
              </td>
              <td>
                <div class="action-buttons" v-if="item.registration.isUsing === 0">
                  <button class="approve-button" @click="handleApprove(item)">通过</button>
                  <button class="reject-button" @click="openRejectModal(item)">拒绝</button>
                </div>
                <div v-else-if="item.registration.isUsing === 1">
                  <button class="cancel-button" @click="handleCancelRegistration(item)">取消报名信息</button>
                </div>
                <div v-else>
                  <!-- 未通过的申请不显示操作按钮 -->
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        
        <!-- 分页控件 -->
        <div class="pagination" v-if="totalPages > 1">
          <button 
            :disabled="currentPage === 1" 
            @click="changePage(currentPage - 1)"
            class="page-button"
          >
            上一页
          </button>
          
          <span class="page-info">
            第 {{ currentPage }} 页，共 {{ totalPages }} 页
          </span>
          
          <button 
            :disabled="currentPage === totalPages" 
            @click="changePage(currentPage + 1)"
            class="page-button"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
    
    <!-- 拒绝原因弹窗 -->
    <div class="modal" v-if="showRejectModal">
      <div class="modal-content">
        <h3>拒绝原因</h3>
        <textarea v-model="rejectReason" placeholder="请输入拒绝原因" rows="4"></textarea>
        <div class="modal-actions">
          <button class="cancel-button" @click="showRejectModal = false">取消</button>
          <button class="confirm-button" @click="handleReject">确认</button>
        </div>
      </div>
    </div>
    
    <!-- 成功提示弹窗 -->
    <div class="modal" v-if="showSuccessModal" @click="showSuccessModal = false">
      <div class="modal-content" @click.stop>
        <h3>提交成功</h3>
        <p>报名名单已成功提交！</p>
        <div class="modal-actions">
          <button class="confirm-button" @click="showSuccessModal = false">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.event-register-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  color: #333;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.filter-buttons {
  display: flex;
  gap: 10px;
}

.filter-buttons button {
  background: #ecf0f1;
  color: #333;
  border: none;
  border-radius: 5px;
  padding: 10px 15px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.filter-buttons button.active {
  background: #3498db;
  color: white;
}

.filter-buttons button:hover {
  background: #bdc3c7;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.filter-buttons button.active:hover {
  background: #2980b9;
}

.submit-button {
  background: #27ae60;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-button:hover:not(:disabled) {
  background: #219653;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.submit-button:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.back-button {
  background: #95a5a6;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: #7f8c8d;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.content {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.loading, .empty-state {
  text-align: center;
  font-size: 18px;
  color: #555;
  padding: 40px 20px;
}

.registrations-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

.registrations-table th,
.registrations-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.registrations-table th {
  background-color: #f8f9fa;
  font-weight: bold;
  color: #333;
}

.registrations-table tbody tr:hover {
  background-color: #f5f5f5;
}

.registrations-table td {
  color: #555;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
}

.page-button {
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-button:hover:not(:disabled) {
  background: #2980b9;
  transform: translateY(-2px);
}

.page-button:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.page-info {
  color: #333;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.approve-button {
  background: #27ae60;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  transition: background 0.3s;
}

.approve-button:hover {
  background: #219653;
}

.reject-button {
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  transition: background 0.3s;
}

.reject-button:hover {
  background: #c0392b;
}

.cancel-button {
  background: #e67e22;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  transition: background 0.3s;
}

.cancel-button:hover {
  background: #d35400;
}

.status {
  font-weight: bold;
}

.status.approved {
  color: #27ae60;
}

.status.rejected {
  color: #e74c3c;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  min-width: 400px;
  max-width: 500px;
}

.modal-content h3 {
  margin-top: 0;
  color: #333;
}

.modal-content textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  font-family: inherit;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-button, .confirm-button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-button {
  background: #95a5a6;
  color: white;
}

.cancel-button:hover {
  background: #7f8c8d;
}

.confirm-button {
  background: #3498db;
  color: white;
}

.confirm-button:hover {
  background: #2980b9;
}
</style>